package com.tambapps.p2p.fandem.model

import com.tambapps.p2p.fandem.util.FileUtils
import com.tambapps.p2p.fandem.util.IoSupplier
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream

class SendingFileData(
    fileName: String?, fileSize: Long, checksum: String?,
    // transient because we don't want this serialized when passing them in handshake
    @field:Transient private val inputStreamIoSupplier: IoSupplier<InputStream?>
) : FileData(fileName, fileSize, checksum) {
    constructor(
        fileName: String?, fileSize: Long,
        inputStreamIoSupplier: IoSupplier<InputStream?>
    ) : this(fileName, fileSize, null, inputStreamIoSupplier)

    @Throws(IOException::class)
    fun newInputStream(): InputStream? {
        return inputStreamIoSupplier.get()
    }

    companion object {
        @JvmOverloads
        fun fromFile(file: File, withChecksum: Boolean = true): SendingFileData {
            val checksum: String? = if (withChecksum) {
                try {
                    FileUtils.computeChecksum(file)
                } catch (e: IOException) {
                    throw RuntimeException("Failed to compute file checksum", e)
                }
            } else {
                null
            }
            return SendingFileData(
                file.name,
                file.length(),
                checksum
            ) { FileInputStream(file) }
        }
    }
}
